<script lang="ts" setup>
import axios from 'axios';
import { ref } from 'vue';
import { useRouter } from 'vue-router'

const router = useRouter()

let form = ref({
  username: "",
  password: ""
})

const onSubmit = () => {
  console.log(form.value)
}

// 提交表单
const submitForm = async () => {
  axios.post('http://localhost:8080/auth/login', form.value)
      .then(res => {
        console.log('登录响应:', res.data)
        // 检查 res.data.data 是否存在
        if (res.data && res.data.data) {
          localStorage.setItem("token", res.data.data.token)
          localStorage.setItem("username", res.data.data.userName)
          localStorage.setItem("role", res.data.data.userId)
          router.replace("/")
        } else {
          console.error('登录失败：返回数据格式不正确', res.data);
        }
      })
      .catch(error => {
        console.error('登录失败:', error)
      })
}

</script>

<template>
  <el-form v-model="form">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="form.password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">
        登录
      </el-button>
      <!-- <el-button @click="resetForm(ruleFormRef)">Reset</el-button> -->
    </el-form-item>
  </el-form>
</template>